﻿using AppUIView;
using Global;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AppService
{
    [Injectable(typeof(ILogger), LifeTime.Singleton)]
    public class LoggerService : ILogger
    {
        readonly ReaderWriterLockSlim _logWriteLock = new ReaderWriterLockSlim();

        public void Log(string msg)
        {
            try
            {
                _logWriteLock.EnterWriteLock();
                //基目录
                string fullPath = System.AppDomain.CurrentDomain.BaseDirectory;
                string strNowDate = DateTime.Now.ToString("yyyy-MM-dd");
                //日志存储路径
                string path = fullPath + @"\logs\";
                fullPath = $@"{path}\{strNowDate}.txt";
                if (!System.IO.Directory.Exists(path))
                    Directory.CreateDirectory(path);
                WriteLog(fullPath, msg);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _logWriteLock.ExitWriteLock();
            }
        }

        public void WriteLog(string fullPath, string msg)
        {
            if (!File.Exists(fullPath))
            {
                FileStream fs = new FileStream(fullPath, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + msg);
                sw.Close();
            }
            else
            {
                FileStream fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write);
                StreamWriter brout = new StreamWriter(fs, Encoding.Default);
                brout.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + msg + "\r\n");
                brout.Close();
            }
        }



    }
}
